﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SocketApp
{
    internal class SocketClient
    {
        public void Client()
        {
            TcpClient client = new TcpClient();
            //连接服务端Ip和端口
            client.Client.Connect(IPAddress.Parse("127.0.0.1"), 18200);


            Task.Run(() => ReadDataLoop(client));

            client.Client.Send(Encoding.ASCII.GetBytes("{\"TID\":1111,\"blabla\":{}}"));
        }

        private static async Task ReadDataLoop(TcpClient client)
        {
            while (true)
            {
                if (!client.Connected)
                    break;
                string xxx = "";
                xxx = await ReadData(client);
                Console.WriteLine(xxx);
            }
        }
        private static Task<string> ReadData(TcpClient client)
        {
            string retVal;
            byte[] data = new byte[1024];
            NetworkStream stream = client.GetStream();
            byte[] myReadBuffer = new byte[1024];
            StringBuilder myCompleteMessage = new StringBuilder();
            int numberOfBytesRead = 0;
            do
            {
                numberOfBytesRead = stream.Read(myReadBuffer, 0, myReadBuffer.Length);

                myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));

            } while (stream.DataAvailable);

            retVal = myCompleteMessage.ToString();
            return Task.FromResult(retVal);
        }
    }
}
